<!--
/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-03-27 23:01
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <a-modal
    :title="isAdd ? '新增按钮' : '修改按钮'"
    :visible="show"
    :footer="null"
    width="40%"
    @cancel="$emit('update:show',false)"
  >
    <x-render-form
      v-if="show"
      ref="antForm"
      v-model="formData"
      :form-options="formOptions"
      @form-submit="formSubmitHandler"
    />
  </a-modal>
</template>

<script>
import FormOptions from './options'
import cloneDeep from 'lodash/cloneDeep'

export default {
  name:'XRenderTableBtnDialog',
  inject: ['xDesignTable'],
  props: {
    isAdd: {
      type: Boolean,
      default: true
    },
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {},
      tableBtns: [],
      formOptions: []
    }
  },
  watch: {
    show: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.initForm()
        }
      }
    }
  },
  mounted() {
    this.formOptions = cloneDeep(FormOptions)
    // 默认btn
    this.tableBtns = cloneDeep([])
  },
  methods: {
    initForm() {
      const {isAdd,xDesignTable} = this
      // 新增按钮
      if (isAdd) {
        this.initFormData()
      } else {
        // 修改按钮
        this.formData = xDesignTable.tableBtns[xDesignTable.currentBtnIndex]
      }
    },
    formSubmitHandler(form) {
      if (!form.name || !form.func) {
        this.$message.error('按钮编号或按钮方法名称未填写')
        return
      }
      const {isAdd,xDesignTable} = this
      if (!isAdd) {
        let index = 0
        for (let i = 0; i < xDesignTable.tableBtns.length; i++) {
          const formBtn = xDesignTable.tableBtns[i]
          if (formBtn.primaryId === form.primaryId) {
            index = i
            break
          }
        }
        xDesignTable.tableBtns.splice(index, 1, form)
      } else {
        xDesignTable.tableBtns.push(form)
      }
      this.initFormData()
      this.$emit('update:show', false)
    },
    initFormData() {
      const {xDesignTable} = this
      // 重置内容
      this.formData = {
        sort: xDesignTable.tableBtns.length,
        name: Date.now() + '',
        primaryId: 'xAntTable' + Date.now()
      }
    }
  }
}
</script>

<style scoped>

</style>
